package com.gaodun.hk.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gaodun.hk.common.response.BasicResponse;
import com.gaodun.hk.common.response.IResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author fengyamin
 * @date 2020/04/14
 **/
@RestControllerAdvice(basePackages = {"com.gaodun.hk.web"})
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        body = body instanceof IResponse ? body : BasicResponse.create(0, "success", body);
        if (!MediaType.APPLICATION_JSON.equals(selectedContentType) && !MediaType.APPLICATION_JSON_UTF8.equals(selectedContentType)) {
            body = JSON.toJSONString(body,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteBigDecimalAsPlain,
                    SerializerFeature.WriteDateUseDateFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteEnumUsingToString,
                    SerializerFeature.DisableCircularReferenceDetect);
        }
        return body;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
}

